<script setup lang="ts">
import { ref, onMounted } from 'vue';
import QRCode from 'qrcode';
import { pullMiniQrcode } from '../api/my';

const isLoggedIn = ref(false);
const qrCode = ref('');
const qrPollingInterval = ref<number | null>(null);
const favoriteList = ref([]);
const hasItems = ref(false);
const userInfo = ref({
  avatar: '',
  username: '未登录'
});

const showLoginModal = ref(false);

const handleAvatarClick = () => {
  if (!isLoggedIn.value) {
    showLoginModal.value = true;
    generateQRCode();
  }
};

const closeLoginModal = () => {
  showLoginModal.value = false;
  stopPolling();
};

const generateQRCode = async () => {
  try {
    // uuid 随机数，去掉中间的横线
    const uuid = crypto.randomUUID().replace(/-/g, '');
    const response = await pullMiniQrcode(uuid);
    qrCode.value = response.data.data;
  } catch (error) {
    console.error('生成二维码失败:', error);
  }
};

const startPolling = () => {
  qrPollingInterval.value = window.setInterval(async () => {
    try {
      // TODO: 轮询登录状态
      // const response = await checkLoginStatus();
      // if (response.data.isLoggedIn) {
      //   isLoggedIn.value = true;
      //   stopPolling();
      //   fetchFavoriteList();
      // }
    } catch (error) {
      console.error('检查登录状态失败:', error);
    }
  }, 2000);
};

const stopPolling = () => {
  if (qrPollingInterval.value) {
    clearInterval(qrPollingInterval.value);
    qrPollingInterval.value = null;
  }
};

const fetchFavoriteList = async () => {
  try {
    // TODO: 从API获取收藏列表
    // const response = await getFavoriteList();
    // favoriteList.value = response.data;
    // hasItems.value = favoriteList.value.length > 0;
  } catch (error) {
    console.error('获取收藏列表失败:', error);
  }
};

const readStory = (id: number) => {
  // TODO: 跳转到故事详情页
};

const unfavorite = async (id: number) => {
  try {
    // TODO: 调用取消收藏API
    // await cancelFavorite(id);
    // await fetchFavoriteList();
  } catch (error) {
    console.error('取消收藏失败:', error);
  }
};

const discoverMore = () => {
  // TODO: 跳转到发现页面
};

onMounted(() => {
  if (!isLoggedIn.value) {
    generateQRCode();
  } else {
    fetchFavoriteList();
  }
});
</script>

<template>
  <div class="container mx-auto px-4 py-8 flex justify-start">
    <!-- 用户信息区域 -->
    <div class="bg-white/80 backdrop-blur-md rounded-2xl p-6 mb-6">
      <div class="flex items-center space-x-4" @click="handleAvatarClick">
        <div class="w-16 h-16 rounded-full overflow-hidden cursor-pointer hover:opacity-80 transition-opacity">
          <img v-if="isLoggedIn && userInfo.avatar" :src="userInfo.avatar" alt="用户头像" class="w-full h-full object-cover">
          <div v-else class="w-full h-full bg-gray-200 flex items-center justify-center">
            <img src="https://unpkg.com/lucide-static@latest/icons/user.svg" class="w-8 h-8 text-gray-400" alt="默认头像">
          </div>
        </div>
        <div>
          <h2 class="text-lg font-semibold">{{ userInfo.username }}</h2>
          <p v-if="!isLoggedIn" class="text-sm text-gray-500">点击头像登录</p>
        </div>
      </div>
    </div>

    <!-- 功能列表 -->
    <div class="space-y-4">
      <!-- 我的收藏 -->
      <div class="bg-white/80 backdrop-blur-md rounded-2xl p-4">
        <h3 class="font-semibold mb-2 flex items-center">
          <img src="https://unpkg.com/lucide-static@latest/icons/heart.svg" class="w-5 h-5 mr-2" alt="收藏">
          我的收藏
        </h3>
        <div v-if="isLoggedIn">
          <!-- 收藏列表 -->
          <div class="space-y-4" v-if="hasItems">
            <div v-for="item in favoriteList" :key="item.id" class="bg-white/90 rounded-xl p-4 shadow-sm flex items-center space-x-4">
              <img :src="item.thumbnail" :alt="item.title" class="w-16 h-16 rounded-xl object-cover">
              <div class="flex-1">
                <h3 class="font-semibold">{{ item.title }}</h3>
                <p class="text-sm text-gray-500">收藏于：{{ item.date }}</p>
              </div>
              <div class="flex space-x-2">
                <img src="https://unpkg.com/lucide-static@latest/icons/book-open.svg" class="w-6 h-6 text-purple-600 cursor-pointer" alt="阅读" @click="readStory(item.id)">
                <img src="https://unpkg.com/lucide-static@latest/icons/heart-off.svg" class="w-6 h-6 text-red-500 cursor-pointer" alt="取消收藏" @click="unfavorite(item.id)">
              </div>
            </div>
          </div>
          <!-- 空状态 -->
          <div v-else class="text-center py-4">
            <img src="https://unpkg.com/lucide-static@latest/icons/heart.svg" class="w-12 h-12 mx-auto mb-2 text-gray-400" alt="空收藏">
            <p class="text-gray-500">暂无收藏的故事</p>
            <button @click="discoverMore" class="mt-4 px-6 py-2 bg-purple-600 text-white rounded-full text-sm font-medium">去发现更多故事</button>
          </div>
        </div>
        <div v-else class="text-center py-4 text-gray-500">
          请先登录查看收藏
        </div>
      </div>
    </div>

    <!-- 登录弹窗 -->
    <div v-if="showLoginModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div class="bg-white rounded-2xl p-8 max-w-sm w-full mx-4">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-xl font-bold">扫码登录</h2>
          <img src="https://unpkg.com/lucide-static@latest/icons/x.svg" class="w-6 h-6 cursor-pointer" alt="关闭" @click="closeLoginModal">
        </div>
        <div class="qr-code-container mx-auto w-48 h-48 mb-4">
          <img v-if="qrCode" :src="qrCode" alt="登录二维码" class="w-full h-full">
          <div v-else class="w-full h-full bg-gray-200 rounded-lg animate-pulse"></div>
        </div>
        <p class="text-gray-600 text-center">请使用手机扫描二维码登录</p>
      </div>
    </div>
  </div>
</template>